#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    trayMenu=nullptr;
    tray=nullptr;
    sharedMemory=nullptr;

    user.awake();
    if(user.needSave)
    {
        ui->account->setText(user.account);
        ui->passwd->setText(user.passwd);
        ui->saved->setChecked(true);
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::createTray()
{
    trayMenu=new QMenu(this);
    trayMenu->addAction(QStringLiteral("退出"),QApplication::quit);

    tray=new QSystemTrayIcon(this);
    tray->setIcon(QIcon(":/share.ico"));
    tray->setContextMenu(trayMenu);
    tray->setToolTip(QString("%1 [%2] 正在运行").arg(SP_NAME).arg(SP_VER));
    tray->show();
}

void Widget::awake()
{
    sharedMemory=new QSharedMemory(SHM_KEY,this);
    profile=getConnection(P_DB_HOST,P_DB_PORT,
                          P_DB_USER,P_DB_PASSWD,P_DB_DBNAME);

    fetchData();
    createTray();
    this->hide();
}

void Widget::fetchData()
{
    if(!dataSource.isEmpty())
        dataSource.clear();

    if(!profile.isOpen())
        profile.open();

    QSqlQuery query;
    query.exec(QString("select entry,host,port,user,passwd,db from %1")
               .arg(P_DATASOURCE));
    while (query.next()) {
        QString entry=query.value(0).toString();
        if(entry.isEmpty())
            continue;

        QString host=query.value(1).toString();
        int port=query.value(2).toInt();
        if(port == 0)
            port=3306;
        QString user=query.value(3).toString();
        QString passwd=query.value(4).toString();
        QString dbName=query.value(5).toString();

        QJsonObject obj={
            {"host",host},
            {"port",port},
            {"user",user},
            {"passwd",passwd},
            {"db",dbName}
        };
        dataSource.insert(entry,obj);
    }
    updateToMemory();
}

void Widget::updateToMemory()
{
    if(dataSource.isEmpty())
        return;

    if(sharedMemory->isAttached())
        sharedMemory->detach();

    QBuffer buffer;
    buffer.open(QBuffer::ReadWrite);

    QDataStream out(&buffer);
    out << dataSource;
    int size=buffer.size();
    if(!sharedMemory->create(size))
    {
        return;
    }
    else{
        sharedMemory->lock();
        // 定义char变量 一个接受sharedMemory  一个接收buffer数据
        char *to = static_cast<char*>(sharedMemory->data());
        const char *from = buffer.data().constData();
        //共享内存段就是一段普通内存，用C语言标准函数memcpy()复制内存段。
        //将bufffer 数据写入共享内存中
        memcpy(to,from,qMin(size,sharedMemory->size()));
        //解锁共享内存段
        sharedMemory->unlock();
    }
}

void Widget::on_btn_login_clicked()
{
    auto name=ui->account->text().trimmed();
    auto passwd=ui->passwd->text().trimmed();

    if(name.isEmpty() || passwd.isEmpty())
    {
        MESSAGE_DETAIL_EMPTY
    }

    user.account=name;
    user.passwd=passwd;
    if(user.checkLoginInfo())
    {
        awake();
        tray->showMessage("认证通过","OA认证通过，ULogin开始运行");
    }else{
        QMessageBox::warning(this,"认证失败","OA认证失败，无法继续操作，程序现在退出");
        qApp->quit();
    }
}

void Widget::on_saved_stateChanged(int state)
{
    if(ui->account->text().trimmed().isEmpty() ||
            ui->passwd->text().trimmed().isEmpty())
    {
        ui->saved->setCheckState(Qt::Unchecked);
        return;
    }

    if(state == Qt::Checked)
        user.needSave=true;
    else
        user.needSave=false;

    user.saveFlag();
}
